# Generated by Django 2.2.12 on 2020-08-18 14:28

from django.contrib.auth import get_user_model
from django.db import migrations
from rolepermissions.checkers import has_role
from rolepermissions.roles import assign_role, clear_roles

from defivelo.roles import DV_AVAILABLE_ROLES


def user_set_collaborator_and_reset_roles(apps, schema_editor):
    # We can't import the Person model directly as it may be a newer
    # version than this migration expects. We use the historical version.
    User = get_user_model()
    for user in User.objects.all():
        hadrole = False
        for rolepair in DV_AVAILABLE_ROLES:
            rolestr = rolepair[0]
            if rolestr and has_role(user, rolestr):
                clear_roles(user)
                assign_role(user, rolestr)
                hadrole = True

        if not hadrole and (user.profile.formation or user.profile.actor):
            # Give collaborator to all monitors and actors
            clear_roles(user)
            assign_role(user, "collaborator")


class Migration(migrations.Migration):
    dependencies = [
        ("user", "0060_reset_all_roles"),
    ]

    operations = [
        migrations.RunPython(
            user_set_collaborator_and_reset_roles, migrations.RunPython.noop
        ),
    ]
